<template>
    <div class="commp-table-total-box">
        <div>
            <div class="condition-vxe-box" :class="conditionBtnRow?'condition-btn-row':''">
                <vxe-form :data="formData" @submit="searchEvent" @reset="resetEvent" v-if="formItem.length" :key="formDataKey">
                    <vxe-form-item v-for="(item,index) in formItem" field="name" :title="item.label+':'" :key="index">
                        <template #default="{ data }" v-if="!item.type">
                            <vxe-input v-if="!item.slotName" v-model="data[item.model]" type="text" :placeholder="item.placeholder?item.placeholder:'请输入'+item.label"></vxe-input>
                            <slot v-else :name="item.slotName" :data="data" ></slot>
                        </template>
                        <template #default="{ data }" v-else>
                            <!-- <vxe-select v-model="data[item.model]" :placeholder="item.placeholder?item.placeholder:'请选择'+item.label">
                                <vxe-option v-for="(nope,nIndex) in item.selectArr" :key="nIndex" :value="nope.itemValue" :label="nope.itemText"></vxe-option>
                            </vxe-select> -->
                            <a-date-picker
                                v-if="item.type == 'datePicker'"
                                @change="($event)=>{onChangeDatePicker($event,item.format,item.model)}" 
                                :format="item.format"
                                v-model:value="data[item.model]"
                            />
                            <compSelector
                                v-else
                                :key="compSelectorKey"
                                v-model="data[item.model]"
                                :compType="item.type"
                                :defaultValue="item.defaultValue"
                                :placeholder="item.label"
                                :options="item.options?item.options:''"
                                :dictionaryType="item.dictionaryType?item.dictionaryType:''"
                                :separateAreas="item.separateAreas?item.separateAreas:''"
                                @selectHandleChange="selectHandleChange($event,item.model,item.convert)"
                            />
                        </template>
                    </vxe-form-item>
                    <vxe-form-item>
                        <template>
                            <vxe-button type="submit" status="primary" content="查询"></vxe-button>
                            <vxe-button type="reset" content="重置"></vxe-button>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item>
                        <template #default="{ data }">
                                <slot name="querButton" :data="data" ></slot>
                            </template>
                    </vxe-form-item>
                </vxe-form>
                <div class="push-button-vxe">
                    <vxe-form>
                        <template #default="{ data }">
                            <slot name="externalOperations" :data="data" ></slot>
                        </template>
                    </vxe-form>
                </div>
                
            </div>
        </div>
        <vxe-table
          border
          stripe
          :maxHeight="gridOptions.height"
          :loading="loading"
          :column-config="{resizable: true}"
          :row-config="{isHover: true}"
          :checkbox-config="{labelField: 'id', highlight: true, range: true}"
          :data="gridOptions.data"
        >
            <vxe-column v-for="(item,index) in columns" :title="item.title" :field="item.field" :width="item.width">
                <template #default="{ row }" v-if="item.slots">
                    <slot :name="item.slots.default" :row="row"></slot>
                </template>
                <template #default="{ row }" v-else>
                    {{ row[item.field] }}
                </template>
            </vxe-column>
        </vxe-table>
    </div>
</template>
<script>
import { axios } from '@/utils/request'
import { mapState } from 'vuex'
import XEUtils from 'xe-utils'
import compSearchCriteria from '../compSearchCriteria/compSearchCriteria'
import compSelector from '../compSelector/compSelector.vue'
export default {
    components:{
        compSearchCriteria,
        compSelector
    },
    props:{
        config:{
            type:Object,
            default:{},
            required:false,
        },
        formItem:{
            type:Array,
            default:[],
            required:false,
        },
        tableData:{
            type:Array,
            default:[],
            required:false,
        },
        scopedSlots:{
            type:Array,
            default:[],
            required:false,
        },
        columns:{
            type:Array,
            default:[],
            required:false,
        },
        serverSorter:{
            type:Boolean,
            default:true,
            required:false,
        },
        adaptiveHeight:{//自适应高度
            type:Boolean,
            default:false,
            required:false,
        },
        toBoolean: {
            // 把配置的值 转为 boolean
            type: Object,
            default: () => {
                return {
                isFalse: ['0', 'n', 'N', 0],
                isTrue: ['1', 'y', 'Y', 1]
                };
            },
            required:false,
        },
        parameterData:{
            type:Object,
            default:()=>{},
            required:false,
        },
        conditionBtnRow:{//按钮和搜索条件在一行
            type:Boolean,
            default:false,
            required:false,
        }
    },
    data(){
        return{
            formDataKey:null,
            compSelectorKey:null,
            formData: {},
            gridOptions: {
                loading:false,
                border: true,
                showHeaderOverflow: true,
                showOverflow: true,
                keepSource: true,
                id:'vxeTable'+new Date().getTime(),
                columnConfig: {
                  resizable: true
                },
                height: this.config.height?this.config.height:600,
                maxHeight:this.adaptiveHeight?1000:0,
                rowId: this.config.rowId,
                sortConfig: {
                  trigger: 'cell',
                  remote: true,
                  defaultSort: {
                    field: 'name',
                    order: 'desc'
                  }
                },
                filterConfig: {
                  remote: true
                },
                pagerConfig: {
                  pageSize: this.config.pageSize?this.config.pageSize:10,
                  pageSizes: [5, 15, 20, 50, 100, 200, 500, 1000],
                  currentPage:1,
                  total:0,
                  autoHidden:this.config.autoHidden?this.config.autoHidden:false,
                },
                checkboxConfig: {
                    // labelField: 'id',
                    reserve: true,
                    highlight: true,
                    range: this.config.selectType=='radio'?false:true,
                    checkMethod:(val)=>{
                        if(this.config.isPdf){
                            return val.row[this.config.suffix.key] == this.config.suffix.value
                        }else{
                            return true
                        }
                         
                    }
                },
                radioConfig:{
                    reserve: true,
                    highlight: true,
                    range: this.config.selectType=='radio'?true:false,
                },
                customConfig:{

                },
                toolbarConfig: {
                    // custom: true,
                  slots: {
                    buttons: 'toolbar_buttons'
                  }
                },
                treeConfig:{//树形结构配置项
                    transform:this.config.treeConfig?(this.config.treeConfig.transform?true:false):false,
                    rowField:this.config.treeConfig?(this.config.treeConfig.rowField?this.config.treeConfig.rowField:''):'',
                    parentField:this.config.treeConfig?(this.config.treeConfig.parentField?this.config.treeConfig.parentField:''):'',
                    indent:20,
                },
                columns: this.columns,
                data: this.tableData,

            },
            isBoolean:[],
            scopedSlots:this.scopedSlots,
            renderingCompleted:false,
        }
    },
    computed: {
    },
    watch:{
        config(newValue,oldValue){
            this.getData(this.formData,this.gridOptions.pagerConfig)
        },
        // formData(){
        //     this.getData(this.formData,this.gridOptions.pagerConfig)
        // },
        parameterData:{
            handler (newValue,oldValue){
                //console.log('新的表格有传进来参数吗？',newValue)
                if(newValue){
                    this.getData({...this.formData,...newValue},this.gridOptions.pagerConfig)
                }
                
            },
            // deep:true,//深度监听输入框输入就会一直刷新表格
            
        },
        adaptiveHeight:{
            handler (newValue,oldValue){
                if(newValue){
                    this.getData({...this.formData},this.gridOptions.pagerConfig)
                }
                
            },
        }
    },
    mounted(){
        // slots: { header: 'name_header', default: 'default_name' }
        this.gridOptions.columns.forEach((item) => {
            item.slots && this.scopedSlots.push(item.slots);
            item.isBoolean && item.key && this.isBoolean.push(item.key);
        });
        this.getData(this.formData,this.gridOptions.pagerConfig)
    },
    updated(){
        //console.log('更新后')
        this.renderingCompleted = true
        this.$emit('updatedChange', 1)
    },
    methods: {
        async getData(params, pagerConfig, sorter){
            return new Promise((resolve, reject) => {
                this.renderingCompleted = false
                this.gridOptions.loading = true
                let sorterData = {}
                if(sorter){
                    if(this.serverSorter && sorter.field){
                        sorterData = {orderItem:sorter.columnKey,orderType:sorter.order}
                        this.$emit('sorterChange',sorterData,sorter)
                    }
                }
                axios({
                    url: this.config.api,
                    method:'get' ,
                    params: {
                        pageNo:pagerConfig.currentPage,
                        pageSize:pagerConfig.pageSize,
                        fywflcode:this.config.fywflcode,
                        ...sorterData,
                        ...this.parameterData,
                        ...this.config.paramet,
                        ...params,
                    },
                    url_1:this.config.urlType?'':'outside',
                    url_2:this.config.urlType?'outside':''
                }).then((res) => {
                    if (res.code === 200 && !this.tableData.length) {
                        if(res.result.records){
                            //console.log('表格列表数据',res.result.records)
                            res.data = res.result.records
                            if (!Array.isArray(res.data)) {
                                res.data = [];
                            }
                            this.gridOptions.pagerConfig.total = res.result.total || 0;

                            if (this.isBoolean.length) {
                                this.gridOptions.data = res.data.map((item) => {
                                    this.isBoolean.forEach((key) => {
                                    if (this.toBoolean.isTrue.indexOf(item[key]) > -1) {
                                        item[key] = true;
                                    } else if (this.toBoolean.isFalse.indexOf(item[key]) > -1) {
                                        item[key] = false;
                                    }
                                    });
                                    return item;
                                });
                            } else {
                                this.gridOptions.data = res.data;
                            }
                        }
                        if(res.result.wjjlList){
                            this.gridOptions.data = res.result.wjjlList
                            this.gridOptions.pagerConfig.total = res.result.wjjlList.length
                        }
                        if(Array.isArray(this.config.listData) && this.config.listData.length == 2){
                            let obj = res.result[this.config.listData[0]]
                            if(obj[this.config.listData[1]]){
                                this.gridOptions.data = obj[this.config.listData[1]]
                                this.gridOptions.pagerConfig.total = obj[this.config.listData[1]].length
                            }else{
                                this.gridOptions.data = []
                                this.gridOptions.pagerConfig.total = 0
                            }
                            
                        }
                        if(Array.isArray(this.config.listData) && this.config.listData.length == 3){
                            let obj = res.result[this.config.listData[0]]
                            let obj1 = obj[this.config.listData[1]]
                            if(obj1[this.config.listData[2]]){
                                this.gridOptions.data = obj1[this.config.listData[2]]
                                this.gridOptions.pagerConfig.total = obj1[this.config.listData[2]].length
                            }else{
                                this.gridOptions.data = []
                                this.gridOptions.pagerConfig.total = 0
                            }
                        }
                        if(!Array.isArray(this.config.listData) && this.config.listData && res.result[this.config.listData]){
                            //console.log('当前表格指定列表数据',this.config.listData)
                            this.gridOptions.data = res.result[this.config.listData]
                            this.gridOptions.pagerConfig.total = res.result[this.config.listData].length
                        }
                        if(this.config.listData){
                            if(!Array.isArray(this.config.listData) && !res.result[this.config.listData]){
                                this.gridOptions.data = []
                                this.gridOptions.pagerConfig.total = 0
                            }
                            
                        }
                        if(this.adaptiveHeight && this.gridOptions.pagerConfig.total>2){
                            this.config.height = (this.gridOptions.pagerConfig.total + 1) * 48
                        }
                    }else{
                        this.gridOptions.pagerConfig.total = this.tableData.length
                        this.gridOptions.data = this.tableData
                    }
                    
                    this.gridOptions.loading = false; // 数据请求完成标识
                    resolve(!this.gridOptions.loading);
                });
            });
        },
        searchEvent () {//查询
            //console.log('是你在刷吗？')
            // const $grid = this.$refs.xGrid
            // $grid.commitProxy('query')
            //console.log(this.config)
            this.$emit('searchEvent',this.formData)
            this.getData({...this.formData,...this.config.paramet},this.gridOptions.pagerConfig)
            
        },
        resetEvent () {//重置
            this.$emit('resetEvent')
            // const $grid = this.$refs.xGrid
            // $grid.commitProxy('reload')
            this.formData = {}
            this.getData({},{currentPage:1,pageSize:this.gridOptions.pagerConfig.pageSize})
            this.compSelectorKey = Date.now()
            this.formDataKey = Date.now()
            
        },
        checkboxChange(val){//选择
            //console.log(val)
            //console.log('当前选择',val.records)
            this.$emit('checkboxChange',val.records)
        },
        radioChange(val){
            //console.log('当前选择',val)
            this.$emit('radioChange',val)
        },
        pageChange(val){//分页
            this.gridOptions.pagerConfig.currentPage = val.currentPage
            this.gridOptions.pagerConfig.pageSize = val.pageSize
            this.getData(this.formData,this.gridOptions.pagerConfig)
        },
    }
}
</script>
<style lang="less">
.commp-table-total-box{
    overflow: hidden !important;
    .vxe-header--row{
        background: #dee5ed !important;
    }
    .vxe-form--item-content{
        .theme--primary{
            border: 1px solid #5ca3e5 !important;
            background-color: #5ca3e5 !important;
            color: #fff !important;
        }
    }
    .condition-vxe-box{
        width: 100%;
        display: flex;
        flex-direction: column;
        margin:0 20px;
        .vxe-form .vxe-form--item{
            padding: 0;
            padding-bottom: 5px;
            padding-right: 5px;
        }
    }
    .push-button-vxe{
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }
    .vxe-checkbox--icon{
        color: #5ca3e5 !important;
        font-weight:normal !important;
    }
    .vxe-table--body-wrapper{
        ::-webkit-scrollbar {
            width: 5px !important;
        }
    }
    .vxe-table--render-default.border--full .vxe-body--column, 
    .vxe-table--render-default.border--full .vxe-footer--column, 
    .vxe-table--render-default.border--full .vxe-header--column{
        background-image:linear-gradient(#d9d9d9,#d9d9d9),linear-gradient(#d9d9d9,#d9d9d9);
    }
    .vxe-form--item-title-label{
        color: #000 !important;
    }
    // .vxe-table--render-default .vxe-cell{
    //     padding: 0 !important;
    // }
}
.commp-vxe-table-box{
    
    
    th,td,tr{
        height: 40px !important;
        color: #000 !important;
        // #d9d9d9
    }
    .vxe-table--render-default .vxe-body--column.col--ellipsis,
     .vxe-table--render-default .vxe-footer--column.col--ellipsis,
      .vxe-table--render-default .vxe-header--column.col--ellipsis,
     .vxe-table--render-default.vxe-editable .vxe-body--column{
        height: 40px !important;
        overflow: hidden !important;
     }
    
}
.adaptive-height-box{
    .vxe-table--fixed-right-wrapper ,.scrolling--middle{
        height: 100% !important;
    }
}
</style>
